import React, { useEffect, useState } from 'react';
import { createGlobalStyle } from "antd-style";
import { ProRouter, type ProRouterProps, type NavigateFunction } from "@yaf/router";
import { ProAppWrapper, InitModalMountPoint } from "@yaf/pro-ui";
import { request } from '@yaf/request';

import { permission, EnumAuthKey, prompt, getGlobalConfig } from "@/service"
import { getAppRoutes, setEnv, getEnv, EnumRouter, noValidateLoginRoutes, noValidateMenuPermissions, ThemeConfigProvider, } from "@/constants";
import { getUserInfo, logout } from "@/components/app/sys/pages/login/api";

// 引入tailwindcss
import "tailwindcss/tailwind.css";

interface AppProps {
  appRouterProps?: ProRouterProps;
}

const App: React.FC<AppProps> = (props) => {
  const { appRouterProps, proAppWrapperProps } = useGlobalConfig(props);

  return <ProAppWrapper {...proAppWrapperProps}>
    <ProRouter {...appRouterProps} />
    <InitModalMountPoint />
    {prompt.initMountPoint()}
  </ProAppWrapper>
}

export default () => {
  const GlobalStyle = getGlobalStyle();

  return <ThemeConfigProvider>
    <App />
    <GlobalStyle />
  </ThemeConfigProvider>
}

/**
 * 初始化全局配置
 */
const useGlobalConfig = ({ appRouterProps, }: AppProps) => {
  const [loading, setLoading] = useState(false);

  // 设置request http client的配置
  request.setRequestConf({ apiDomain: getEnv().apiDomain, apiResponseCode: getEnv().apiResponseCode, });
  

  useEffect(() => {
    setLoading(true);
    // 用于获取全局的系统配置
    getGlobalConfig().then(resp => {
      setEnv({ globalConfig: resp.data })

      // 用于登录后获取用户配置
      const currentPathname = trimLSRlash(window.location.pathname);
      if (!noValidateLoginRoutes.map(item => trimLSRlash(item)).includes(currentPathname)) {
        getUserInfo().then(() => setLoading(false)).catch(() => setLoading(false))
      } else {
        setLoading(false);
      }

    }).catch(() => {
      setLoading(false);
    })

  }, []);

  return {
    appRouterProps: Object.assign({
      rootPath: EnumRouter.rootRoute,
      redirectPath: EnumRouter.appRoot,
      mounted: (_navigate: NavigateFunction) => {
        request.setRequestConf({
          redirectLogin: () => {
            logout();
            // 1. 清除登录用户信息
            permission.loginUser.clear();

            // 2. 清除请求token
            request.removeToken()

            window.location.href = EnumRouter.login;
            // if (document.querySelector("#sk-mount-modal")) document.querySelector("#sk-mount-modal").remove()
          }
        })
      },
      appRoutes: getAppRoutes(),
      authorized: {
        // 路由权限
        permissions: validatePermission(),
        noVerifyLoginPathList: noValidateLoginRoutes,
        noLoginRedirectPath: EnumRouter.login,
        checkLogin: asyncCheckLogin,
      }
    }, appRouterProps),

    proAppWrapperProps: {
      loading,
      allowBrowser: getEnv().allowBrowser,
      lang: {
        type: "zh",
        intlMessages: {}
      }
    },
  }
}

// 校验权限
const validatePermission = () => {
  // TODO 暂不校验菜单权限
  return null

  if (permission.isSuperAdmin()) return null;

  // 路由列表
  const pathList = Object.keys(EnumRouter)
    // @ts-ignore
    .filter((path) => permission.can(EnumAuthKey[path]))
    // @ts-ignore
    .map((key) => EnumRouter[key])
  // .filter(path => typeof path === "string")

  return [
    ...noValidateMenuPermissions,
    ...pathList
  ];
}

// 异步检查登录
const asyncCheckLogin = async () => {
  // const loginUserInfo = permission.loginUser.get();
  // const { id } = loginUserInfo.user;
  // globalStore.setUserLogined(!!userId);
  // globalStore.setLoginUserInfo(loginUserInfo);

  return true;
}

// 清除左右斜线
const trimLSRlash = (str: string) => str.replace(/\/$/, "").replace(/^\//, "");

// 全局样式
const getGlobalStyle = () => {
  return createGlobalStyle`
    * {
      box-sizing: border-box;
    }

    html {
      height: 100%;
      body {
        height: 100%;
        margin: 0;
        padding: 0;
        color: ${(p) => p.theme.colorText};
        background: ${(p) => p?.theme?.custom?.bodyBgColor};
        > #wrapper {
          height: 100%;
          & > .ant-app{
            height: 100%;
            position: relative;
          }
        }
      }
    }
  `
}
